<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2017/12/27  9:17
 */

namespace app\api\logic;

use think\Cache;
use app\api\BaseModel;
use app\api\logic\Order;
use think\Db;

class HttpClient
{
    // Request vars
    var $host;
    var $port;
    var $path;
    var $method;
    var $postdata = '';
    var $cookies = array();
    var $referer;
    var $accept = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
    var $accept_encoding = 'gzip';
    var $accept_language = 'en-us';
    var $user_agent = 'Incutio HttpClient v0.9';
    var $timeout = 20;
    var $use_gzip = true;
    var $persist_cookies = true;
    var $persist_referers = true;
    var $debug = false;
    var $handle_redirects = true;
    var $max_redirects = 5;
    var $headers_only = false;
    var $username;
    var $password;
    var $status;
    var $headers = array();
    var $content = '';
    var $errormsg;
    var $redirect_count = 0;
    var $cookie_host = '';

    function __construct($host, $port = 80)
    {
        $this->host = $host;
        $this->port = $port;
    }

    function get($path, $data = false)
    {
        $this->path = $path;
        $this->method = 'GET';
        if ($data) {
            $this->path .= '?' . $this->buildQueryString($data);
        }
        return $this->doRequest();
    }

    function post($path, $data)
    {
        $this->path = $path;
        $this->method = 'POST';
        $this->postdata = $this->buildQueryString($data);
        return $this->doRequest();
    }

    function buildQueryString($data)
    {
        $querystring = '';
        if (is_array($data)) {
            foreach ($data as $key => $val) {
                if (is_array($val)) {
                    foreach ($val as $val2) {
                        $querystring .= urlencode($key) . '=' . urlencode($val2) . '&';
                    }
                } else {
                    $querystring .= urlencode($key) . '=' . urlencode($val) . '&';
                }
            }
            $querystring = substr($querystring, 0, -1); // Eliminate unnecessary &
        } else {
            $querystring = $data;
        }
        return $querystring;
    }

    function doRequest()
    {
        if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) {
            switch ($errno) {
                case -3:
                    $this->errormsg = 'Socket creation failed (-3)';
                case -4:
                    $this->errormsg = 'DNS lookup failure (-4)';
                case -5:
                    $this->errormsg = 'Connection refused or timed out (-5)';
                default:
                    $this->errormsg = 'Connection failed (' . $errno . ')';
                    $this->errormsg .= ' ' . $errstr;
                    $this->debug($this->errormsg);
            }
            return false;
        }
        socket_set_timeout($fp, $this->timeout);
        $request = $this->buildRequest();
        $this->debug('Request', $request);
        fwrite($fp, $request);
        $this->headers = array();
        $this->content = '';
        $this->errormsg = '';
        $inHeaders = true;
        $atStart = true;
        while (!feof($fp)) {
            $line = fgets($fp, 4096);
            if ($atStart) {
                $atStart = false;
                if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
                    $this->errormsg = "Status code line invalid: " . htmlentities($line);
                    $this->debug($this->errormsg);
                    return false;
                }
                $http_version = $m[1];
                $this->status = $m[2];
                $status_string = $m[3];
                $this->debug(trim($line));
                continue;
            }
            if ($inHeaders) {
                if (trim($line) == '') {
                    $inHeaders = false;
                    $this->debug('Received Headers', $this->headers);
                    if ($this->headers_only) {
                        break;
                    }
                    continue;
                }
                if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) {
                    continue;
                }
                $key = strtolower(trim($m[1]));
                $val = trim($m[2]);
                if (isset($this->headers[$key])) {
                    if (is_array($this->headers[$key])) {
                        $this->headers[$key][] = $val;
                    } else {
                        $this->headers[$key] = array($this->headers[$key], $val);
                    }
                } else {
                    $this->headers[$key] = $val;
                }
                continue;
            }
            $this->content .= $line;
        }
        fclose($fp);
        if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') {
            $this->debug('Content is gzip encoded, unzipping it');
            $this->content = substr($this->content, 10);
            $this->content = gzinflate($this->content);
        }
        if ($this->persist_cookies && isset($this->headers['set-cookie']) && $this->host == $this->cookie_host) {
            $cookies = $this->headers['set-cookie'];
            if (!is_array($cookies)) {
                $cookies = array($cookies);
            }
            foreach ($cookies as $cookie) {
                if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) {
                    $this->cookies[$m[1]] = $m[2];
                }
            }
            $this->cookie_host = $this->host;
        }
        if ($this->persist_referers) {
            $this->debug('Persisting referer: ' . $this->getRequestURL());
            $this->referer = $this->getRequestURL();
        }
        if ($this->handle_redirects) {
            if (++$this->redirect_count >= $this->max_redirects) {
                $this->errormsg = 'Number of redirects exceeded maximum (' . $this->max_redirects . ')';
                $this->debug($this->errormsg);
                $this->redirect_count = 0;
                return false;
            }
            $location = isset($this->headers['location']) ? $this->headers['location'] : '';
            $uri = isset($this->headers['uri']) ? $this->headers['uri'] : '';
            if ($location || $uri) {
                $url = parse_url($location . $uri);
                return $this->get($url['path']);
            }
        }
        return true;
    }

    function buildRequest()
    {
        $headers = array();
        $headers[] = "{$this->method} {$this->path} HTTP/1.0";
        $headers[] = "Host: {$this->host}";
        $headers[] = "User-Agent: {$this->user_agent}";
        $headers[] = "Accept: {$this->accept}";
        if ($this->use_gzip) {
            $headers[] = "Accept-encoding: {$this->accept_encoding}";
        }
        $headers[] = "Accept-language: {$this->accept_language}";
        if ($this->referer) {
            $headers[] = "Referer: {$this->referer}";
        }
        if ($this->cookies) {
            $cookie = 'Cookie: ';
            foreach ($this->cookies as $key => $value) {
                $cookie .= "$key=$value; ";
            }
            $headers[] = $cookie;
        }
        if ($this->username && $this->password) {
            $headers[] = 'Authorization: BASIC ' . base64_encode($this->username . ':' . $this->password);
        }
        if ($this->postdata) {
            $headers[] = 'Content-Type: application/x-www-form-urlencoded';
            $headers[] = 'Content-Length: ' . strlen($this->postdata);
        }
        $request = implode("\r\n", $headers) . "\r\n\r\n" . $this->postdata;
        return $request;
    }

    function getStatus()
    {
        return $this->status;
    }

    function getContent()
    {
        return $this->content;
    }

    function getHeaders()
    {
        return $this->headers;
    }

    function getHeader($header)
    {
        $header = strtolower($header);
        if (isset($this->headers[$header])) {
            return $this->headers[$header];
        } else {
            return false;
        }
    }

    function getError()
    {
        return $this->errormsg;
    }

    function getCookies()
    {
        return $this->cookies;
    }

    function getRequestURL()
    {
        $url = 'http://' . $this->host;
        if ($this->port != 80) {
            $url .= ':' . $this->port;
        }
        $url .= $this->path;
        return $url;
    }

    function setUserAgent($string)
    {
        $this->user_agent = $string;
    }

    function setAuthorization($username, $password)
    {
        $this->username = $username;
        $this->password = $password;
    }

    function setCookies($array)
    {
        $this->cookies = $array;
    }

    function useGzip($boolean)
    {
        $this->use_gzip = $boolean;
    }

    function setPersistCookies($boolean)
    {
        $this->persist_cookies = $boolean;
    }

    function setPersistReferers($boolean)
    {
        $this->persist_referers = $boolean;
    }

    function setHandleRedirects($boolean)
    {
        $this->handle_redirects = $boolean;
    }

    function setMaxRedirects($num)
    {
        $this->max_redirects = $num;
    }

    function setHeadersOnly($boolean)
    {
        $this->headers_only = $boolean;
    }

    function setDebug($boolean)
    {
        $this->debug = $boolean;
    }

    function quickGet($url)
    {
        $bits = parse_url($url);
        $host = $bits['host'];
        $port = isset($bits['port']) ? $bits['port'] : 80;
        $path = isset($bits['path']) ? $bits['path'] : '/';
        if (isset($bits['query'])) {
            $path .= '?' . $bits['query'];
        }
        $client = new HttpClient($host, $port);
        if (!$client->get($path)) {
            return false;
        } else {
            return $client->getContent();
        }
    }

    function quickPost($url, $data)
    {
        $bits = parse_url($url);
        $host = $bits['host'];
        $port = isset($bits['port']) ? $bits['port'] : 80;
        $path = isset($bits['path']) ? $bits['path'] : '/';
        $client = new HttpClient($host, $port);
        if (!$client->post($path, $data)) {
            return false;
        } else {
            return $client->getContent();
        }
    }

    function debug($msg, $object = false)
    {
        if ($this->debug) {
            print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> ' . $msg;
            if ($object) {
                ob_start();
                print_r($object);
                $content = htmlentities(ob_get_contents());
                ob_end_clean();
                print '<pre>' . $content . '</pre>';
            }
            print '</div>';
        }
    }
}

class System extends BaseModel
{
    /**
     * 开关商铺
     */
    public function open()
    {
        $shop_id = $this->user['shopid'];
        $db_shop = db("shop");
        $shop = $db_shop->where("id='$shop_id'")->field("isopen")->find();
        if ($shop['isopen'] == 0) {
            $data['isopen'] = 1;
        } else {
            $data['isopen'] = 0;
        }
        $res = $db_shop->where("id='$shop_id'")->update($data);
        if (!$res) return array("message" => '系统繁忙');
        return $data;
    }

    /**
     * 店内分类
     */
    public function category()
    {

        $shop_id = $this->user['shopid'];
        $db_shop = db("category_goods");
        $data = $db_shop->where("shop_id='$shop_id' and status=1")->field("id,name,des,img,sort")->order('sort desc')->select();
        return $data;
    }

    /**
     * 添加修改分类
     */
    public function category_edit()
    {
        (new \app\api\validate\System())->checkCategoryEdit();
        $shop_id = $this->user['shopid'];
        $db_shop = db("category_goods");
        $data['name'] = $this->requestData['name'];
        $data['des'] = $this->requestData['des'];
        $data['sort'] = $this->requestData['sort'];
        $data['shop_id'] = $shop_id;
        $file = request()->file('image');
        if ($file) {
            $info = $file->move('./static/uploads');
            if ($info) {
                $data['img'] = '/' . $info->getSaveName();
            }
        }

        if (isset($this->requestData['id']) && !empty($this->requestData['id'])) {
            $res = $db_shop->where("id=" . $this->requestData['id'])->update($data);
        } else {
            $res = $db_shop->insert($data);
        }
        if ($res === false) return array("message" => '操作失败');
        return array();
    }

    /**
     * 分类详情
     */
    public function category_detail()
    {
        $db_shop = db("category_goods");
        $where['id'] = $this->requestData['id'];
        $where['shop_id'] = $this->user['shopid'];
        $cate = $db_shop->where($where)->find();

        return $cate;
    }

    /**
     * 删除分类
     */
    public function category_del()
    {
        (new \app\api\validate\System())->checkCategoryDel();
        $shop_id = $this->user['shopid'];
        $db_shop = db("category_goods");
        $data['shop_id'] = $shop_id;
        $data['id'] = $this->requestData['id'];
        $category = $db_shop->where($data)->find();
        if (!$category) return array("message" => '记录不存在');

        $goods_where['cid'] = $this->requestData['id'];
        $goods_where['status'] = '1';
        $goods = db("goods")->where($goods_where)->count();
        if ($goods > 0) return ['message' => '该分类还有商品，不能删除!'];

        $res = $db_shop->where($data)->update(['status' => '-1']);
        if ($res === false) return array("message" => '操作失败');
        return array();
    }

    /**
     * 商品列表
     */
    public function goods()
    {
        $shop_id = $this->user['shopid'];
        $db_goods = db("goods");
        $data['shop_id'] = $shop_id;
        if (isset($this->requestData['status']) && !empty($this->requestData['status'])) {
            $data['status'] = $this->requestData['status'];
        } else {
            $data['status'] = array("gt", -1);
        }
        if (isset($this->requestData['cid']) && !empty($this->requestData['cid'])) {
            $data['cid'] = $this->requestData['cid'];
        }
        if (isset($this->requestData['name'])) {
            $data['name'] = array("like", '%' . $this->requestData['name'] . '%');
        }
        $data['status'] = 1;
        $p = isset($this->requestData['page']) ? $this->requestData['page'] : '1';
        $size = isset($this->requestData['limit']) ? $this->requestData['limit'] : '10';
        $goods = $db_goods->where($data)->page($p, $size)->order("id desc")->select();
        $db_order = db("order");
        foreach ($goods as &$v) {
            $v['image'] = IMG_PATH . $v['image'];
            $or['og.goods_id'] = $v['id'];
            $or['o.status'] = '3';
            $or['o.finish_time'] = array('between', [time() - 30 * 24 * 60 * 60, time()]);
            $v['ordernum'] = $db_order->alias("o")
                ->join("order_goods og", "og.order_id=o.id")
                ->where($or)->count();
        }
        $count = $db_goods->where($data)->count();
        $result['list'] = $goods;
        $result['count'] = $count;;
        $result['page_num'] = $p;
        $result['page_limit'] = $size;
        return $result;
    }

    /**
     * 商品详情
     */
    public function goods_detail()
    {
        (new \app\api\validate\System())->checkCategoryDel();
        $db_goods = db("goods");
        $where['id'] = $this->requestData['id'];
        //$where['shop_id']= $this->user['shopid'];
        $goods = $db_goods->where($where)->find();
        $pinimgs = [];
        if ($goods['image']) {
            $goods['image'] = IMG_PATH . $goods['image'];
            array_push($pinimgs, $goods['image']);
        }
        if (!empty($goods['imgs'])) {
            $goodsimgs = unserialize($goods['imgs']);
            $goods['imgs'] = [];
            foreach ($goodsimgs as $k => &$file) {
                $goods['imgs'][$k] = IMG_PATH . $file;
                array_push($pinimgs, IMG_PATH . $file);
            }
        } else {
            $goods['imgs'] = [];
        }
        $goods['pinimgs'] = $pinimgs;
        if (empty($goods['keepday'])) {
            $goods['keepday'] = '';
        }
        $commission = db('config')->where(['id' => 6])->value('value');
//        if($commission){
        $goods['commission'] = $commission;
//        }
        $db_goods_option = db("goods_option");
        $db_goods_param = db("goods_param");
        $goods['option'] = $db_goods_option->where("goodsid=" . $goods['id'])->select();
        $param = $db_goods_param->field("id,title,param")->where("goodsid=" . $goods['id'])->select();
        foreach ($param as &$d) {
            $d['param'] = unserialize($d['param']);
        }
        $goods['params'] = $param;
        return $goods;
    }

    /**
     * 添加修改商品
     */
    public function goods_edit()
    {
        (new \app\api\validate\System())->checkGoodsEdit();
        $shop_id = $this->user['shopid'];
        $db_goods = db("goods");
        $data = [
            'name' => $this->requestData['name'],
            'des' => isset($this->requestData['des']) ? $this->requestData['des'] : '',
            'keepday' => isset($this->requestData['keepday']) ? $this->requestData['keepday'] : '',
            'label' => $this->requestData['label'],
            'cid' => $this->requestData['cid'],
            'price' => $this->requestData['price'],
            'oldprice' => $this->requestData['oldprice'],
            'stock' => $this->requestData['stock'],
            'unit' => isset($this->requestData['unit']) ? $this->requestData['unit'] : '',
            "shop_id" => $shop_id,
        ];

        $file = request()->file('image');
        if ($file) {
            $info = $file->move('./static/uploads');
            if ($info) {
                $data['image'] = '/' . $info->getSaveName();
            }
        }
        if (isset($this->requestData['id']) && !empty($this->requestData['id'])) {
            $id = $this->requestData['id'];
            $goods = $db_goods->where("id=" . $this->requestData['id'])->find();
            if (isset($data['image'])) {
                if (is_file(ROOT_PATH . 'public/static/uploads/' . $goods['image'])) {
                    unlink(ROOT_PATH . 'public/static/uploads/' . $goods['image']);
                }
            }
            Db::startTrans();
            try {
                $res = $db_goods->where("id=" . $this->requestData['id'])->update($data);
                if ($res === false) throw new \Exception('修改失败');

                if (isset($this->requestData['specs'])) {
                    $specs = json_decode($this->requestData['specs'], 1);

                    //if(!empty($specs) && is_array($specs)){

                    $is_empty_specs = $this->is_empty_specs($specs);

                    if ($is_empty_specs) {
                        throw new \Exception('商品规格有空值');
                    }

                    $spec_id_array = array_column($specs, 'id');

                    $db_option = db("goods_option");

                    //先清空商品规格在重新插数据
                    $where['goodsid'] = $this->requestData['id'];
                    $db_option->where($where)->delete();


                    foreach ($specs as $k => $v) {
                        $option = array(
                            "title" => $v['title'],
                            "stock" => $v['stock'],
                            "price" => $v['price'],
                            "goodsid" => $this->requestData['id']
                        );

                        if (!empty($v['id'])) {
                            $option['id'] = $v['id'];
                        }

                        $op_res = $db_option->insert($option);
                        if ($op_res === false) throw new \Exception('修改规格失败');
                    }
                    //}
                }

                if (isset($this->requestData['params'])) {
                    $params = json_decode($this->requestData['params'], 1);

                    if (!empty($params) && is_array($params)) {
                        $is_empty_params = $this->is_empty_params($params);

                        if ($is_empty_params) {
                            throw new \Exception('商品属性有空值');
                        }

                        $param_id_array = array_column($params, 'id');
                        $db_param = db("goods_param");
                        unset($where);
                        $where['goodsid'] = $this->requestData['id'];
                        $db_param->where($where)->delete();

                        foreach ($params as $k => $v) {
                            $param = array(
                                "title" => $v['title'],
                                "param" => serialize($v['param']),
                                "goodsid" => $this->requestData['id']
                            );

                            if (!empty($v['id'])) {
                                $param['id'] = $v['id'];
                            }

                            $pa_res = $db_param->insert($param);
                            if ($pa_res === false) throw new \Exception('修改属性失败');
                            unset($param);
                        }
                    }

                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return array("message" => $e->getMessage());
            }
            $result['id'] = $id;
            return $result;
        } else {
            Db::startTrans();
            try {
                $res = $db_goods->insertGetId($data);
                $id = $res;
                if (!$res) throw new \Exception('发布失败');

                if (isset($this->requestData['specs'])) {
                    $specs = json_decode($this->requestData['specs'], 1);
                    if (!empty($specs) && is_array($specs)) {
                        $is_empty_specs = $this->is_empty_specs($specs);

                        if ($is_empty_specs) {
                            throw new \Exception('商品规格有空值');
                        }

                        $db_option = db("goods_option");
                        foreach ($specs as $k => $v) {
                            $option = array(
                                "title" => $v['title'],
                                "stock" => $v['stock'],
                                "price" => $v['price'],
                                "goodsid" => $res,
                            );
                            $op_add = $db_option->insert($option);
                            if (!$op_add) throw new \Exception('添加规格失败');
                        }
                    }
                }

                if (isset($this->requestData['params'])) {

                    $params = json_decode($this->requestData['params'], 1);

                    if (!empty($params) && is_array($params)) {
                        $is_empty_params = $this->is_empty_params($params);

                        if ($is_empty_params) {
                            throw new \Exception('商品属性有空值');
                        }

                        $db_param = db("goods_param");
                        foreach ($params as $k => $v) {
                            $param = array(
                                "title" => $v['title'],
                                "param" => serialize($v['param']),
                                "goodsid" => $res,
                            );
                            $pa_add = $db_param->insert($param);
                            if (!$pa_add) throw new \Exception('添加属性失败');
                        }
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return array("message" => $e->getMessage());
            }
            if ($res === false) return array("message" => '操作失败');
            $result['id'] = $id;
            return $result;
        }
    }

    /**
     * delete商品详情图
     */
    public function goods_imgs_del()
    {
        $gid = isset($this->requestData['id']) ? $this->requestData['id'] : '0';
        $i = $this->requestData['index'];
        if ($i === false) return ['删除失败!'];
        $db_good = db('goods');
        $db_good_images = $db_good->where("id=" . $gid)->field('id,imgs')->find();
        if (!empty($db_good_images) && !empty($db_good_images['imgs'])) {
            $db_good_images_array = unserialize($db_good_images['imgs']);
            $pic = ROOT_PATH . 'public/static/uploads/' . $db_good_images_array[$i];
            if (file_exists($pic)) {
                @unlink($pic);
            }
            unset($db_good_images_array[$i]);
            if (!empty($db_good_images)) {
                $data['imgs'] = serialize($db_good_images_array);
            } else {
                $data['imgs'] = '';
            }

            $res = $db_good->where("id=" . $gid)->update($data);


        }
        if (isset($res)) {
            $goods = $db_good->where("id=" . $gid)->field('id,imgs')->find();
            if (!empty($goods['imgs'])) {
                $goodsimgs = unserialize($goods['imgs']);
                $goods['imgs'] = [];
                foreach ($goodsimgs as $k => &$file) {
                    $goods['imgs'][$k] = IMG_PATH . $file;
                }
            } else {
                $goods['imgs'] = [];
            }
            return $goods;
        }
    }

    /**
     * 添加修改商品详情图
     */
    public function goods_imgs_edit()
    {
        $file = request()->file('images');
        if (!$file) return array("message" => '请上传图片');
        $info = $file->move('./static/uploads');

        $gid = isset($this->requestData['id']) ? $this->requestData['id'] : '0';

        $db_good_images_array = [];
        $db_good = db('goods');
        $db_good_images = $db_good->where("id=" . $gid)->field('id,imgs')->find();

        if (!empty($db_good_images)) {
            if (!empty($db_good_images['imgs'])) {
                $db_good_images_array = unserialize($db_good_images['imgs']);
            }
        } else {
            return ['message' => '非法id！'];
        }

        $db_good_images_array[] = '/' . $info->getSaveName();

        $update['imgs'] = serialize($db_good_images_array);

        $res = $db_good->where("id=" . $gid)->update($update);

        if ($res === false) return array("message" => '操作失败');
        return $db_good_images_array;
    }

    /*
    *检测商品规格是否有空值
    */
    public function is_empty_specs($specs)
    {
        $is_empty_specs = false;
        foreach ($specs as $v) {
            if (empty($v['title']) || empty($v['stock']) || empty($v['price'])) {
                $is_empty_specs = true;
                break;
            }
        }

        return $is_empty_specs;
    }

    /**
     *检测商品属性是否有空值
     */
    public function is_empty_params($params)
    {
        $is_empty_params = false;
        foreach ($params as $v) {
            if (empty($v['title']) || empty($v['param'])) {
                $is_empty_params = true;
                break;
            }
        }

        return $is_empty_params;
    }

    /**
     * 设置登录密码
     */
    public function setPassword()
    {
        (new \app\api\validate\System())->setPassword();
        $shop_id = $this->user['shopid'];
        $db_shop = db("shop");
        $mobile = $db_shop->where("id='$shop_id'")->value('mobile');
        $code = trim($this->requestData['code']);
        if (base64_encode($code) != Cache::get($mobile)) {
            return array('message' => '验证码错误');
        }
        $password = trim($this->requestData['password']);
        $repassword = trim($this->requestData['repassword']);
        if ($password != $repassword) return array("message" => '两次密码不一致');
        $pass['password'] = md5($password);
        $res = $db_shop->where("id='$shop_id'")->update($pass);
        if ($res === false) return array("message" => '操作失败');
    }

    /**
     * 设置支付密码
     */
    public function set_paypwd()
    {
        (new \app\api\validate\System())->setPassword();
        $shop_id = $this->user['shopid'];
        $db_shop = db("shop");
        $code = trim($this->requestData['code']);
        if (base64_encode($code) != Cache::get('code')) {
            return array('message' => '验证码错误');
        }
        $password = trim($this->requestData['password']);
        $repassword = trim($this->requestData['repassword']);
        if ($password != $repassword) return array("message" => '两次密码不一致');
        $pass['pay_pw'] = $password;
        $res = $db_shop->where("shop_id='$shop_id' and status=1")->update($pass);
        if ($res === false) return array("message" => '操作失败');
    }

    public function bind()
    {
        (new \app\api\validate\System())->Bind();
        $shop_id = $this->user['shopid'];
        $db_shop = db("shop");
        $code = trim($this->requestData['code']);
        if (base64_encode($code) != Cache::get('code')) {
            return array('message' => '验证码错误');
        }
        $pass['mobile'] = trim($this->requestData['mobile']);
        if ($pass['mobile'] != Cache::get('mobile')) {
            return array('message' => '手机号码不一致');
        }
        $res = $db_shop->where("shop_id='$shop_id' and status=1")->update($pass);
        if ($res === false) return array("message" => '操作失败');
    }

    public function opentime()
    {
        $type = isset($this->requestData['type']) ? $this->requestData['type'] : 0;
        $shop_id = $this->user['shopid'];
        if ($type == 1) {
            $opentime = array(
                array("starttime" => '00:00', 'endtime' => '23:59')
            );
        } else {
            // if (!isset($this->requestData['starttime']) || !isset($this->requestData['endtime'])) return array('message'=>'请填写时间');
            //     $starttime = $this->requestData['starttime'];
            //     if (!is_array($starttime))  return array('message'=>'请传数组');
            //     $endtime = $this->requestData['endtime'];
            //     if (count($starttime) != count($endtime))  return array('message'=>'缺少参数');
            // $opentime=array();
            //         foreach ($starttime as $k => $v) {
            //             $opentime[] = array(
            //                 "starttime" => $v,
            //                 "endtime" => $endtime[$k]
            //             );
            //         }
            if (!isset($this->requestData['time_string'])) return array('message' => '请填写时间');
            $time_string = json_decode($this->requestData['time_string'], 1);
            foreach ($time_string as $k => $v) {
                $opentime[] = array(
                    "starttime" => $v['starttime'],
                    "endtime" => $v['endtime']
                );
            }
        }
        if (isset($opentime)) {
            $pass['open_time'] = serialize($opentime);
        } else {
            $pass['open_time'] = '';
        }

        $res = db('shop')->where("id='$shop_id'")->update($pass);
        if ($res === false) return array("message" => '操作失败');
    }

    public function deliverytime()
    {
        $type = isset($this->requestData['type']) ? $this->requestData['type'] : 0;
        $shop_id = $this->user['shopid'];
        if ($type == 1) {
            $opentime = array(
                array("starttime" => '00:00', 'endtime' => '23:59')
            );
        } else {
            // if (!isset($this->requestData['starttime']) || !isset($this->requestData['endtime'])) return array('message'=>'请填写时间');
            //     $starttime = $this->requestData['starttime'];
            //     if (!is_array($starttime))  return array('message'=>'请传数组');
            //     $endtime = $this->requestData['endtime'];
            //     if (count($starttime) != count($endtime))  return array('message'=>'缺少参数');
            // $opentime=array();
            //         foreach ($starttime as $k => $v) {
            //             $opentime[] = array(
            //                 "starttime" => $v,
            //                 "endtime" => $endtime[$k]
            //             );
            //         }
            if (!isset($this->requestData['time_string'])) return array('message' => '请填写时间');
            $time_string = json_decode($this->requestData['time_string'], 1);
            foreach ($time_string as $k => $v) {
                $opentime[] = array(
                    "starttime" => $v['starttime'],
                    "endtime" => $v['endtime']
                );
            }
        }
        if (isset($opentime)) {
            $pass['delivery_time'] = serialize($opentime);
        } else {
            $pass['delivery_time'] = '';
        }

        $res = db('shop')->where("id='$shop_id'")->update($pass);
        if ($res === false) return array("message" => '操作失败');
    }

    public function tell()
    {
        if (!isset($this->requestData['tell']) || empty($this->requestData['tell'])) return array('message' => '请填写订餐电话');
        if (!is_array($this->requestData['tell'])) return array('message' => '请传数组');
        $tell = implode(",", $this->requestData['tell']);
        // $tell=serialize($this->requestData['tell']);
        $pass['tell'] = $tell;
        $shop_id = $this->user['shopid'];
        $res = db('shop')->where("id='$shop_id'")->update($pass);
        if ($res === false) return array("message" => '操作失败');
    }

    public function des()
    {
        if (!isset($this->requestData['des'])) return array('message' => '请填写简介');
        $pass['des'] = $this->requestData['des'];
        $shop_id = $this->user['shopid'];
        $res = db('shop')->where("id='$shop_id'")->update($pass);
        if ($res === false) return array("message" => '操作失败');
    }

    public function book()
    {
        $shop_id = $this->user['shopid'];
        $db_shop = db('shop');
        $shop = $db_shop->field('isbook')->where("id='$shop_id'")->find();
        if ($shop['isbook'] == 0) {
            $data['isbook'] = 1;
        } else {
            $data['isbook'] = 0;
        }
        $res = $db_shop->where("id='$shop_id'")->update($data);
        if ($res === false) return array("message" => '操作失败');
        return $data;
    }

    public function send()
    {
        $shop_id = $this->user['shopid'];
        $db_shop = db('shop');
        $shop = $db_shop->field('issend')->where("id='$shop_id'")->find();
        $data['send_fee'] = $this->requestData['fee'];
        if ($shop['issend'] == 0) {
            $data['issend'] = 1;
        } else {
            $data['issend'] = 0;
        }
        $res = $db_shop->where("id='$shop_id'")->update($data);
        if ($res === false) return array("message" => '操作失败');
        return $data;
    }

    public function full_distribution()
    {
        if (!isset($this->requestData['full_distribution'])) return array('message' => '请填写配送费');
        $pass['full_distribution'] = $this->requestData['full_distribution'];
        $shop_id = $this->user['shopid'];
        $res = db('shop')->where("id='$shop_id'")->update($pass);
        if ($res === false) return array("message" => '操作失败');
    }

    public function del_images()
    {
        $sel = db('shop')->where(['id' => $this->user['shopid']])->value('images');
        if (!empty($sel)) {
            db('shop')->where(['id' => $this->user['shopid']])->update(['images' => '']);
        }
    }

    public function save_images()
    {
        $file = request()->file('image');
        if (!$file) return array("message" => '请上传图片');
        $info = $file->move('./static/uploads');

        $shopid = $this->user['shopid'];

        $db_shop_images_array = [];
        $db_shop = db('shop');
        $db_shop_images = $db_shop->where("id=" . $this->user['shopid'])->field('images')->find();

        if (!empty($db_shop_images)) {
            $db_shop_images_array = unserialize($db_shop_images['images']);
        }

        $db_shop_images_array[] = $info->getSaveName();

        $update['images'] = serialize($db_shop_images_array);

        $res = $db_shop->where("id=" . $this->user['shopid'])->update($update);

        if ($res === false) return array("message" => '操作失败');
        return $db_shop_images_array;
    }

    public function auth()
    {
        (new \app\api\validate\System())->auth();
        $data['shopname'] = $this->requestData['shopname'];
        $data['license_term'] = $this->requestData['license_term'];
        $data['food_term'] = $this->requestData['food_term'];
        $license_name = $this->requestData['license_name'];
        $food_name = $this->requestData['food_name'];
        if ($license_name != $food_name) return array("message" => '营业执照法人与食品安全证书法人不一致');
        $data['license_remark'] = isset($this->requestData['license_remark']) ? $this->requestData['license_remark'] : '';
        $data['food_remark'] = isset($this->requestData['food_remark']) ? $this->requestData['food_remark'] : '';
        $data['islicense'] = 0;
        $data['issafetygrade'] = 0;
        $data['status'] = 2;
        $data['realname'] = $license_name;

        $shop_id = $this->user['shopid'];
        $db_shop = db('shop');
        $res = $db_shop->where("id='$shop_id'")->update($data);
        if ($res === false) return array("message" => '操作失败');
    }

    public function license_image()
    {
        $license = request()->file('license');
        if (!$license) return array("message" => '请上传营业执照');
        $info = $license->validate(['size' => 1560078, 'ext' => 'jpg,png,jpeg'])->move(ROOT_PATH . 'public/static/certificates');
        if ($info) {
            $data['license'] = $info->getSaveName();
        } else {
            return array("message" => $license->getError());
        }

        $shop_id = $this->user['shopid'];
        $db_shop = db('shop');
        $res = $db_shop->where("id='$shop_id'")->update($data);
        if ($res === false) return array("message" => '操作失败');
    }

    public function food_image()
    {
        $food = request()->file('food');
        if (!$food) return array("message" => '请上传食品安全证书');
        $info = $food->validate(['size' => 1560078, 'ext' => 'jpg,png,jpeg'])->move(ROOT_PATH . 'public/static/certificates');
        if ($info) {
            $data['foodlicense'] = $info->getSaveName();
        } else {
            return array("message" => $food->getError());
        }

        $shop_id = $this->user['shopid'];
        $db_shop = db('shop');
        $res = $db_shop->where("id='$shop_id'")->update($data);
        if ($res === false) return array("message" => '操作失败');
    }

    /**
     * 评论列表
     */
    public function comment()
    {
        $p = isset($this->requestData['page']) ? $this->requestData['page'] : '1';
        $size = isset($this->requestData['limit']) ? $this->requestData['limit'] : '10';
        $type = isset($this->requestData['type']) ? $this->requestData['type'] : '0';
        $where['c.shop_id'] = $this->user['shopid'];
        $where['c.status'] = 0;
        if ($type == 1) {
            $where['c.reply'] = null;
        }
        $comment = db("comment")->alias("c")
            ->field("m.nickname,m.headimage,c.*")
            ->join("member m", "m.id=c.uid")
            ->where($where)
            ->order("id desc")
            ->page($p, $size)
            ->select();
        $count = db("comment")->alias("c")
            ->field("m.nickname,m.headimage,c.*")
            ->join("member m", "m.id=c.uid")
            ->where($where)
            ->count();
        foreach ($comment as &$v) {
            $v['create_time'] = date("Y-m-d", $v['create_time']);
            if ($v['images']) {
                $images = unserialize($v['images']);
                $img = [];
                foreach ($images as &$d) {
                    $img[] = IMG_PATH . $d;
                }
                $v['images'] = $img;
            }
        }
        $data['list'] = $comment;
        $data['count'] = $count;;
        $data['page_num'] = $p;
        $data['page_limit'] = $size;
        return $data;
    }

    public function reply()
    {
        (new \app\api\validate\System())->reply();
        $db_comment = db('comment');
        $where['shop_id'] = $this->user['shopid'];
        $where['id'] = $this->requestData['id'];
        $shop = $db_comment->where($where)->find();
        if (!$shop) return array("message" => '记录不存在');
        $data['reply'] = $this->requestData['content'];
        $res = $db_comment->where($where)->update($data);
        if ($res === false) return array("message" => '操作失败');
        return array();
    }

    public function feedback()
    {
        $images[] = cache('$shopid');
        $data['images'] = serialize($images);
        $data['shop_id'] = $this->user['shopid'];
        $data['content'] = $this->requestData['content'];
        $data['create_time'] = TIMESTAMP;
        $db_feedback = db('feedback');
        $res = $db_feedback->insert($data);
        cache('$shopid', null);
        if ($res === false) return array("message" => '操作失败');
    }

    public function basic()
    {
        (new \app\api\validate\System())->basic();
        $images[] = cache('$shopid');
        $data['updateimages'] = serialize($images);
        if (isset($this->requestData['content']) && !empty($this->requestData['content'])) {
            $data['updatecontent'] = $this->requestData['content'];
        }
        $cid = $this->requestData['cid'];
        $cate = db("category_shop")->where("id=" . $cid)->find();
        if (!$cate) return array("message" => '该分类不存在');
        $data['status'] = 2;
        $data['cid'] = $cid;
        $data['shopname'] = $this->requestData['shopname'];;
        $db_shop = db('shop');
        $res = $db_shop->where("id=" . $this->user['shopid'])->update($data);
        cache('$shopid', null);
        if ($res === false) return array("message" => '操作失败');
    }

    public function address()
    {
        (new \app\api\validate\System())->address();
        $data = array(
            'province' => $this->requestData['province'],
            'city' => $this->requestData['city'],
            'county' => $this->requestData['county'],
            'street' => $this->requestData['street'],
            'address' => $this->requestData['address'],
            'status' => 3
        );
        $address = $data['province'] . $data['city'] . $data['county'] . $data['street'] . $data['address'];
        $url = 'http://api.map.baidu.com/cloudgc/v1?address=' . $address . '&ak=4IU3oIAMpZhfWZsMu7xzqBBAf6vMHcoa';
        $res = file_get_contents($url);
        $res = json_decode($res, true);
        $lat = $res['result'][0]['location']['lat'];
        $lng = $res['result'][0]['location']['lng'];
        $data['lat'] = isset($this->requestData['lat']) ? $this->requestData['lat'] : $lat;
        $data['lng'] = isset($this->requestData['lng']) ? $this->requestData['lng'] : $lng;
        $db_shop = db('shop');
        $res = $db_shop->where("id=" . $this->user['shopid'])->update($data);
        if ($res === false) return array("message" => '操作失败');
    }

    public function qrcode()
    {
        $p = isset($this->requestData['page']) ? $this->requestData['page'] : '1';
        $size = isset($this->requestData['limit']) ? $this->requestData['limit'] : '10';
        $db_seat = db("seat");
        $list = $db_seat->field("id,name,qr_code")->where("shop_id=" . $this->user['shopid'])->page($p, $size)->order('id desc')->select();
        foreach ($list as &$v) {
            if ($v['qr_code']) {
                $v['qr_code'] = "http://" . $_SERVER['HTTP_HOST'] . '/static/' . $v['qr_code'];
            }
        }
        $count = $db_seat->where("shop_id=" . $this->user['shopid'])->count();
        return $data = array(
            "list" => $list,
            "page_limit" => $size,
            "count" => $count,
            "page_num" => $p,
        );
    }

    /**
     * 新增
     */
    public function createqrcode()
    {
        $data = array(
            'name' => $this->requestData['name'],
            'shop_id' => $this->user['shopid'],
        );
        Db::startTrans();
        try {
            $seat_result = db('seat')->where(['shop_id' => $this->user['shopid'], 'name' => $this->requestData['name']])->find();
            if (!empty($seat_result)) throw new \Exception('该线路已添加过了，请更改线路名称!');
            $res = db("seat")->insertGetId($data);
            if (!$res) throw new \Exception('添加桌子失败');
            $qrcode['qr_code'] = $this->makeQr($res, $data['shop_id']);
            $res = db("seat")->where("id='$res'")->update($qrcode);
            if (!$res) throw new \Exception('生成二维码失败');
            DB::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return array("message" => $e->getMessage());
        }
        return array("name" => $data['name'], "qr_code" => "http://" . $_SERVER['HTTP_HOST'] . '/static/' . $qrcode['qr_code']);
    }

    /**
     * 二维码
     */
    public function makeQr($table_id, $shop_id)
    {
        //生成二维码图片
        $img_path_binary = $this->Wechatcode($table_id, $shop_id);
        $img_name = md5($img_path_binary);

        //$seat_result = db('seat')->where(['qr_code'=>$img_name])->find();
        //if(!empty($seat_result))return $seat_result['qr_code'];

        $this->checkPath(ROOT_PATH . 'public\static\code');

        $file = fopen(ROOT_PATH . 'public\static\code\\' . $img_name . ".png", "w");//打开文件准备写入
        fwrite($file, $img_path_binary);//写入
        fclose($file);//关闭

        return 'code/' . $img_name . ".png";
    }

    /**
     *   二维码路径
     */
    public function Wechatcode($table_id, $shop_id)
    {
        $result = new \app\api\logic\Wechatcode();
        $result = $result->get_qrcode($table_id, $shop_id);
        return $result;
    }

    /**
     * 检查目录是否可写
     * @param string $path 目录
     * @return boolean
     */
    protected function checkPath($path)
    {
        if (is_dir($path)) {
            return true;
        }
        if (mkdir($path, 0755, true)) {
            return true;
        } else {
            return false;
        }
    }

    public function management()
    {
        $shop_id = $this->user['shopid'];
        $db_shop = db('shop');
        $shop = $db_shop->field('id,shopname,headimage,isopen')->where("id='$shop_id'")->find();
        $shop['headimage'] = IMG_PATH . $shop['headimage'];

        //打印机编号
        $printer_result = db('printer')->where(['shop_id' => $shop_id])->field('printer_id')->find();

        return $data = array(
            "shop" => $shop,
            "order" => $this->order(),
            "price" => $this->sale(),
            "printer" => $printer_result['printer_id']
        );
    }

    public function qrcode_del()
    {
        $id = $this->requestData['id'];
        $db_seat = db("seat");
        $seat = $db_seat->where("id='$id' and shop_id=" . $this->user['shopid'])->find();
        if (is_file(ROOT_PATH . 'public/static/' . $seat['qr_code'])) {
            unlink(ROOT_PATH . 'public/static/' . $seat['qr_code']);
        }
        $del = $db_seat->where("id='$id' and shop_id=" . $this->user['shopid'])->delete();;
        if (!$del) return array("message" => '删除失败');

    }

    /**
     * 完成订单
     */
    public function order()
    {
        $order_db = db("order");
        $today['pay_time'] = array('between', [strtotime(date("Y-m-d")), time()]);
        $today['status'] = ['in', ['1', '2', '3']];
        $today['shop_id'] = $this->user['shopid'];
        $order['today'] = $order_db->where($today)->count();
        $yesterday['pay_time'] = array('between', [strtotime(date("Y-m-d")) - 24 * 60 * 60, strtotime(date("Y-m-d"))]);
        $yesterday['status'] = ['in', ['1', '2', '3']];;
        $yesterday['shop_id'] = $this->user['shopid'];
        $order['yesterday'] = $order_db->where($yesterday)->count();
        return $order;
    }

    /**
     * 订单列表
     */
    public function orderlist()
    {
        $page = isset($this->requestData['page']) ? $this->requestData['page'] : '1';
        $limit = isset($this->requestData['limit']) ? $this->requestData['limit'] : '10';
        $type = isset($this->requestData['type']) ? $this->requestData['type'] : '0';
        $is_print = isset($this->requestData['is_print']) ? $this->requestData['is_print'] : '';
        $keyword = isset($this->requestData['keyword']) ? $this->requestData['keyword'] : '';
        $where = array();
        if (isset($this->requestData['status'])) {
            switch ($this->requestData['status']) {
                case '0':
                    //待付款
                    $where['or.status'] = '0';
                    break;
                case '1':
                    //查询未评价的订单
                    $where['or.iscomment'] = '0';
                    $where['or.status'] = '3';
                    break;
                case '2':
                    //查询已完成的订单
                    $where['or.iscomment'] = '1';
                    $where['or.status'] = '3';
                    break;
                case '3':
                    //查询待发货的订单
                    $where['or.iscomment'] = '0';
                    $where['or.status'] = '1';
                    break;
                case '4':
                    //查询待收货的订单
                    $where['or.iscomment'] = '0';
                    $where['or.status'] = '2';
                    break;
            }
        } else {
            $where['or.status'] = array("neq", '-2');
        }
        if ($type == 1) {
            $where['or.status'] = '1';
            $where['or.type'] = array(['=', '1'], ['=', '2'], ['=', '3'], ['=', '4'], 'or');

        } elseif ($type == 2) {
            $where['or.status'] = '1';
            $where['or.type'] = '1';
        }
        if ($keyword) {
            $where['or.order_sn'] = array("like", '%' . $keyword . '%');
        }
        if (!empty($is_print)) {
            $where['or.is_print'] = $is_print;
        }

        $where['or.shop_id'] = $this->user['shopid'];
        //订单数量
        $db_order = db('order');
        $db_shop = db("shop");
        $count = $db_order->alias('or')
            ->join('shop s', 's.id=or.shop_id')
            ->where($where)
            ->count();

        $order = $db_order->alias('or')
            ->join('shop s', 's.id=or.shop_id')
            ->field('or.id,or.product_name,or.order_sn,or.book_time,or.status,or.type,or.create_time,or.pay_time,or.total_price,or.total_price,or.shop_id,or.iscomment,s.shopname,s.headimage,or.is_print,or.order_ticket')
            ->where($where)
            ->order('or.id desc')
            ->page($page, $limit)
            ->select();
        // ECHO $this->getLastSql();EXIT;
        $order_time_string = config('order_time.expire_in');
        $order_finish = config('order_time.finish');
        foreach ($order as $key => &$value) {
            $value['headimage'] = IMG_PATH . $value['headimage'];
            if ($value['book_time'] && $value['type'] == '1') {
                $value['book_time'] = date('Y-m-d H:i:s', $value['book_time']);
            }
            //购买多少件商品
            $goods_count = db('order_goods')->where(['order_id' => $value['id']])->count();
            $order[$key]['goods_count'] = $goods_count;

            //把过期订单更新完
            if (TIMESTAMP > ($value['create_time'] + $order_time_string) && $value['status'] == '0') {
                $db_order->where(['id' => $value['id'], 'status' => '0'])->update(['status' => '-2']);
                unset($order[$key]);
            }

            $value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
        }
        return array('list' => array_merge($order), 'page_num' => $page, 'page_limit' => $limit, 'count' => $count);
    }

    /**
     * 营业金额
     */
    public function sale()
    {
        $order_db = db("order");
        $today['pay_time'] = array('between', [strtotime(date("Y-m-d")), time()]);
        $today['status'] = ['in', ['1', '2', '3']];
        $today['shop_id'] = $this->user['shopid'];
        $order['today'] = $order_db->where($today)->sum("total_price");
        $yesterday['pay_time'] = array('between', [strtotime(date("Y-m-d")) - 24 * 60 * 60, strtotime(date("Y-m-d"))]);
        $yesterday['status'] = ['in', ['1', '2', '3']];
        $yesterday['shop_id'] = $this->user['shopid'];
        $order['yesterday'] = $order_db->where($yesterday)->sum("total_price");
        $all['status'] = ['in', ['1', '2', '3']];
        $all['shop_id'] = $this->user['shopid'];
        $order['all'] = $order_db->where($all)->sum("total_price");
        return $order;
    }

    /**
     * 绑定银行卡
     */
    public function bindcard()
    {
        (new \app\api\validate\System())->bindcard();
        $db_bankcard = db("bankcard");
        $code = trim($this->requestData['code']);
        if (base64_encode($code) != Cache::get('code')) {
            return array('message' => '验证码错误');
        }
        $data = [
            'name' => $this->requestData['name'],
            'card_num' => $this->requestData['card_num'],
            'bank' => $this->requestData['bank'],
            'mobile' => $this->requestData['mobile'],
            'branch' => $this->requestData['branch'],
            "shop_id" => $this->user['shopid'],
        ];
        $card = $db_bankcard->where("shop_id=" . $this->user['shopid'])->find();
        if ($card) return array("message" => '无需重复绑定');
        $res = $db_bankcard->insert($data);
        if (!$res) return array("message" => '绑定失败');
    }

    /**
     * 银行卡详情
     */
    public function bankdetail()
    {
        $db_bankcard = db("bankcard");
        $card = $db_bankcard->where("shop_id=" . $this->user['shopid'])->find();
        if (!$card) return array("message" => '还没绑定银行卡');
        return $card;
    }

    /**
     * 解绑银行卡
     */
    public function unbundling()
    {
        $db_bankcard = db("bankcard");
        $res = $db_bankcard->where("shop_id=" . $this->user['shopid'])->delete();
        if (!$res) return array("message" => '解绑失败');
    }

    /**
     * 商户零钱
     */
    public function balance()
    {
        $shop = db("shop")->field("balance")->where("id=" . $this->user['shopid'])->find();
        $card = db("bankcard")->field("bank,card_num,name,branch,mobile")->where("shop_id=" . $this->user['shopid'])->find();
        if (!empty($card)) {
            return $data = array("balacne" => $shop['balance'], 'bank' => $card['bank'], 'card_num' => $card['card_num'], 'name' => $card['name'], 'branch' => $card['branch'], 'mobile' => $card['mobile']);
        } else {
            return $data = array("balacne" => $shop['balance'], 'bank' => null, 'card_num' => null);
        }
    }

    /**
     * 申请提现
     */
    public function apply()
    {
        (new \app\api\validate\System())->apply();
        $member = db("shop")->field("balance")->where("id=" . $this->user['shopid'])->find();
        $db_withdrawals = db("withdrawals");
        $config = db("config")->where("id=5")->find();
        $poundage = round(floatval($config['value']) * $this->requestData['money'] / 100, 2);

        if (floatval($this->requestData['money']) <= 0) return array("message" => '提现金额有误');
        if ($member['balance'] < floatval($this->requestData['money'])) return array("message" => '余额不足');
        $db_bankcard = db("bankcard");
        $card = $db_bankcard->where("shop_id=" . $this->user['shopid'])->find();
        $code = isset($this->requestData['code']) ? $this->requestData['code'] : '';
        $code = trim($code);
        if (empty($code)) return ['message' => '验证码为空!'];
        if (base64_encode($code) != Cache::get($card['mobile'])) {
            return array('message' => '验证码错误');
        }
        $data = [
            'shop_id' => $this->user['shopid'],
            'money' => $this->requestData['money'],
            'poundage' => $poundage,
            'paid' => $this->requestData['money'] - $poundage,
            'create_time' => TIMESTAMP,
            "name" => $card['name'],
            "card_num" => $card['card_num'],
            "mobile" => $card['mobile'],
            "bank" => $card['bank'],
            "branch" => $card['branch'],
        ];
        try {
            $res = $db_withdrawals->insert($data);
            if (!$res) throw new \Exception('提现失败');
            $reduce = db("shop")->where("id=" . $this->user['shopid'])->setDec("balance", $this->requestData['money']);
            if (!$reduce) throw new \Exception('扣余额失败');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return array("message" => $e->getMessage());
        }
    }

    /**
     * 提现记录
     */
    public function withdrawals()
    {
        $db_withdrawals = db("withdrawals");
        $p = isset($this->requestData['page']) ? $this->requestData['page'] : '1';
        $size = isset($this->requestData['limit']) ? $this->requestData['limit'] : '10';
        $count = $db_withdrawals->where("shop_id=" . $this->user['shopid'])->count();
        $log = array();
        if ($count > 0) {
            $log = $db_withdrawals->where("shop_id=" . $this->user['shopid'])->page($p, $size)->order("id desc")->select();
            foreach ($log as &$v) {
                $v['create_time'] = date("Y-m-d H:i:s", $v['create_time']);
                if ($v['check_time']) {
                    $v['check_time'] = date("Y-m-d H:i:s", $v['check_time']);
                }
            }
        }
        return array("list" => $log, 'count' => $count, 'page_num' => $p, 'page_limit' => $size);
    }

    /**
     * 自提订单核销
     */
    public function order_write()
    {
        $result = [];
        try {
            if (!isset($this->requestData['id'])) throw new \Exception("订单id参数有误!", 1);
            if (!isset($this->requestData['user_id'])) throw new \Exception("请传用户id", 1);
            $condition['id'] = $this->requestData['id'];
            $condition['user_id'] = $this->requestData['user_id'];
            $order_result = db('order')->where($condition)->find();
            if ($order_result['status'] == '3') throw new \Exception("该订单已领取过了!", 1);
            if (empty($order_result)) throw new \Exception("订单id参数有误!", 1);
            if ($order_result['shop_id'] != $this->user['shopid']) throw new \Exception("该订单你没权限核销!", 1);
            if ($order_result['type'] != '4') throw new \Exception("该订单不是自提订单!", 1);
        } catch (\Exception $e) {
            return array('message' => $e->getMessage());
        }

        Db::startTrans();
        try {
            $order = new Order();

            $order->receive();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return array('message' => $e->getMessage());
        }

    }

    /**
     * 订单详情
     */
    public function orderdetail()
    {
        $condition['o.shop_id'] = $this->user['shopid'];
        $condition['o.id'] = $this->requestData['id'];
        $list = db('order')->alias("o")
            ->join("shop s", "s.id=o.shop_id")
            ->field("s.shopname,s.headimage,o.id,o.order_sn,o.status,pay_type,order_sn,total_price,discount_title,update_time,o.table_name,o.create_time,finish_time,pay_time,o.address,o.mobile,o.realname,o.address,s.province,s.city,s.county,s.street,s.address,o.order_ticket")
            ->where($condition)->find();
        if (empty($list)) return array('message' => '订单不存在');
        $order_time_string = config('order_time.expire_in');
        if (TIMESTAMP < ($list['create_time'] + $order_time_string) and $list['status'] == '0') {
            $list['deadtime'] = $list['create_time'] + $order_time_string - TIMESTAMP;
        } else {
            $list['deadtime'] = 0;
        }
        $where['order_id'] = $list['id'];
        $list['order_goods'] = db('order_goods')
            ->field("goods_price,goods_name,goods_num,param,spec_name,goods_image")
            ->where($where)->select();
        if ($list['create_time']) {
            $list['create_time'] = date("Y-m-d H:i:s", $list['create_time']);
        }
        if ($list['update_time']) {
            $list['update_time'] = date("Y-m-d H:i:s", $list['update_time']);
        }
        if ($list['finish_time']) {
            $list['finish_time'] = date("Y-m-d H:i:s", $list['finish_time']);
        }
        if ($list['pay_time']) {
            $list['pay_time'] = date("Y-m-d H:i:s", $list['pay_time']);
        }
        if ($list['headimage']) {
            $list['headimage'] = IMG_PATH . $list['headimage'];
        }
        foreach ($list['order_goods'] as &$item) {
            $item['goods_image'] = IMG_PATH . $item['goods_image'];
        }
        return $list;
    }

    /**
     * 订单处理
     */
    public function orderdeal()
    {
        $condition['id'] = $this->requestData['id'];
        $condition['shop_id'] = $this->user['shopid'];
        $this->model_order = db('order');
        $order = $this->model_order->where($condition)->find();
        if (!$order) return array('message' => '订单不存在');
        if ($order['status'] != '1') return array('message' => '非待处理状态');
        $res = $this->model_order->where(['id' => $order['id']])->update(['status' => 2, 'send_status' => 2, 'update_time' => TIMESTAMP]);
        if (!$res) return array("message" => '操作失败');
        return array();
    }

    /**
     * 门店信息
     */
    public function info()
    {
        $shop_id = $this->user['shopid'];
        $shop = db("shop")->alias("s")
            ->field("s.id,headimage,shopname,mobile,province,city,county,street,address,tell,images,open_time,delivery_time,c.name,s.des,isbook,issafetygrade,isid,islicense,s.full_distribution,s.lng,s.lat")
            ->join("category_shop c", "c.id=s.cid")
            ->where("s.id='$shop_id'")->find();
        if (!empty($shop['open_time'])) {
            $open_time = unserialize($shop['open_time']);
            $str = '';
            foreach ($open_time as $v) {
                $str .= $v['starttime'] . '-' . $v['endtime'] . ' ';
            }
            $shop['open_time'] = $str;
        } else {
            $shop['open_time'] = '';
        }
        if (!empty($shop['delivery_time'])) {
            $delivery_time = unserialize($shop['delivery_time']);
            $str = '';
            foreach ($delivery_time as $v) {
                $str .= $v['starttime'] . '-' . $v['endtime'] . ' ';
            }
            $shop['delivery_time'] = $str;
        } else {
            $shop['delivery_time'] = '';
        }
        $images = [];
        if (!empty($shop['images'])) {
            $images = unserialize($shop['images']);
        }
        $images = count($images);
        $shop['count'] = $images;
        if (!empty($shop['headimage'])) {
            $shop['headimage'] = IMG_PATH . $shop['headimage'];
        }
        return $shop;
    }

    /**
     * 门店信息
     */
    public function time()
    {
        $shop_id = $this->user['shopid'];
        $shop = db("shop")->alias("s")
            ->field("open_time,tell,delivery_time")
            ->where("s.id='$shop_id'")->find();
        if ($shop['open_time']) {
            $shop['open_time'] = unserialize($shop['open_time']);
            $starttime = $shop['open_time'][0]['starttime'];
            $endtime = $shop['open_time'][0]['endtime'];
            if ($starttime === '00:00' && $endtime === '23:59') {
                $shop['type'] = 1;
            } else {
                $shop['type'] = 0;
            }
        }
        if (!empty($shop['delivery_time'])) {
            $shop['delivery_time'] = unserialize($shop['delivery_time']);
        }
        if ($shop['tell']) {
            $shop['tell'] = explode(",", $shop['tell']);
        }
        return $shop;
    }

    /**
     *   上传店铺
     */
    public function update_headimage()
    {
        $headimage = request()->file('headimage');
        if (!$headimage) return array("message" => '请上传店铺头像');
        $info = $headimage->validate(['size' => 1560078, 'ext' => 'jpg,png,jpeg'])->move(ROOT_PATH . 'public/static/uploads');
        if ($info) {
            $data['headimage'] = $info->getSaveName();
        } else {
            return array("message" => $headimage->getError());
        }

        $result = db("shop")->where("id=" . $this->user['shopid'])->update($data);

        if (!$result) return array('message' => '更新头像失败');
    }

    /**
     *   查询通知设置
     */
    public function shop_notice()
    {
        $notice = db("shop")->field("neworder_notice,preorder_notice")->where("id=" . $this->user['shopid'])->find();
        return $notice;
    }

    /**
     *   新订单通知
     */
    public function neworder_notice()
    {
        $shop_id = $this->user['shopid'];
        $db_shop = db('shop');
        $shop = $db_shop->field('neworder_notice')->where("id='$shop_id'")->find();
        if ($shop['neworder_notice'] == 0) {
            $data['neworder_notice'] = 1;
        } else {
            $data['neworder_notice'] = 0;
        }
        $res = $db_shop->where("id='$shop_id'")->update($data);
        if ($res === false) return array("message" => '操作失败');
        return $data;
    }

    /**
     *   预订单通知
     */
    public function preorder_notice()
    {
        $shop_id = $this->user['shopid'];
        $db_shop = db('shop');
        $shop = $db_shop->field('preorder_notice')->where("id='$shop_id'")->find();
        if ($shop['preorder_notice'] == 0) {
            $data['preorder_notice'] = 1;
        } else {
            $data['preorder_notice'] = 0;
        }
        $res = $db_shop->where("id='$shop_id'")->update($data);
        if ($res === false) return array("message" => '操作失败');
        return $data;
    }

    /**
     *   商品下架
     */
    public function goods_state()
    {
        $data['id'] = $this->requestData['id'];
        $goods = db('goods')->where($data)->find();
        if (!$goods) return array("message" => '记录不存在');
        if ($goods['status'] == 0) {
            $good['status'] = 1;
        } else {
            $good['status'] = 0;
        }
        $res = db('goods')->where($data)->update($good);
        if ($res === false) return array("message" => '操作失败');
        return $good;
    }

    /**
     *   打印机列表
     */
    public function PrinterList()
    {
        $shop_id = $this->user['shopid'];
        $where['shop_id'] = $shop_id;
        $printer = db('printer')->where($where)->select();
        if ($printer) {
            return $printer;
        } else {
            return array("message" => '没有绑定打印机');
        }
    }

    /**
     *   添加打印机
     */
    public function add_list()
    {
        $snlist = $this->requestData['snlist'];
        $type = $this->requestData['type'];
        $printer_type = isset($this->requestData['printer_type'])?$this->requestData['printer_type']:'';

        if(empty($printer_type)) return array("message" => 'printer_type参数为空');

        if(!in_array($printer_type,['1','2'])){
            return array("message" => 'printer_type参数有误');
        }

        $printer = db('printer');

        if($printer->count('*')>=2)return array("message" => '最多添加两个打印机');

        $printer_type_column = $printer->column('printer_type');

        if(!empty($printer_type_column)) {
            if (in_array($printer_type, $printer_type_column)) return array("message" => '该类型打印机已添加过了');
        }

        $content = array(
            'user' => USER,
            'stime' => STIME,
            'sig' => SIG,
            'apiname' => 'Open_printerAddlist',

            'printerContent' => $snlist
        );

        $client = new HttpClient(IP, PORT);
        if (!$client->post(PATH, $content)) {
            return 'error';
        } else {
            $result = $client->getContent();
            $result = json_decode($result, true);
            if (!empty($result['data']['ok'])) {
                $data['shop_id'] = $this->user['shopid'];
                $data['printer_id'] = $snlist;
                $data['type'] = $type;
                $data['printer_type'] = $printer_type;
                db('printer')->insert($data);
                return $result['data']['ok'];
            }
            return array("message" => "绑定失败:".$result['data']['no'][0]);
        }
    }

    /**
     *   删除打印机
     */
    public function del_list()
    {
        $snlist = $this->requestData['snlist'];
        $content = array(
            'user' => USER,
            'stime' => STIME,
            'sig' => SIG,
            'apiname' => 'Open_printerDelList',

            'snlist' => $snlist
        );

        $client = new HttpClient(IP, PORT);
        if (!$client->post(PATH, $content)) {
            return 'error';
        } else {
            $result = $client->getContent();
            $result = json_decode($result, true);
            if (!empty($result['data']['ok'])) {
                $where['shop_id'] = $this->user['shopid'];
                $where['printer_id'] = ['like', '%' . $snlist . '%'];
                db('printer')->where($where)->delete();
                return $result['data']['ok'];
            }
            return array("message" => '删除失败');
        }
    }

    /**
     *   查询打印机状态
     */
    public function queryPrinterStatus($snlist)
    {
        if ($snlist == '') {
            $printer_sn = $this->requestData['snlist'];
        } else {
            $printer_sn = $snlist;
        }
        $msgInfo = array(
            'user' => USER,
            'stime' => STIME,
            'sig' => SIG,
            'apiname' => 'Open_queryPrinterStatus',

            'sn' => $printer_sn
        );

        $client = new HttpClient(IP, PORT);
        if (!$client->post(PATH, $msgInfo)) {
            return 'error';
        } else {
            $result = $client->getContent();
            $result = json_decode($result, true);

            //正确例子：
            //{"msg":"ok","ret":0,"data":"离线","serverExecutedTime":9}
            //{"msg":"ok","ret":0,"data":"在线，工作状态正常","serverExecutedTime":9}
            //{"msg":"ok","ret":0,"data":"在线，工作状态不正常","serverExecutedTime":9}
            if ($result['data'] == "在线，工作状态不正常。" || $result['data'] == "离线。" || empty($result['data'])) {
                return array("message" => '打印机异常，请检查!');
            }
            //return $result;
        }
    }

    /**
     *   打印小票订单
     */
    public function wp_print($param = '')
    {
        if ($param == '') {

            $shop_id = db('order')->where(['id'=>$this->requestData['order_id']])->value('shop_id');
            $printer = db('printer')->where(['shop_id'=>$shop_id,'printer_type'=>'1'])->find();
            $printer = explode("#", $printer['printer_id']);

            if(empty($printer[0]))return array('message'=>'未绑定打印机');

            //前端调用打印
            $printer_sn = $printer[0];
            $shopid = $this->requestData['shopid'];
            $shipping_address = $this->requestData['shipping_address'];
            $realname = isset($this->requestData['realname']) ? $this->requestData['realname'] : '';
            $mobile = isset($this->requestData['mobile']) ? $this->requestData['mobile'] : '';
            $order_id = $this->requestData['order_id'];

        } else {
            //支付回调直接打印
            $printer_sn = $param['snlist'];
            $shopid = $param['shopid'];
            $shipping_address = $param['shipping_address'];
            $realname = $param['realname'];
            $mobile = $param['mobile'];
            $order_id = $param['order_id'];
        }

        $condition['id'] = $order_id;
        $list = db('order')->where($condition)->find();
        $where['order_id'] = $list['id'];
        $list['order_goods'] = db('order_goods')
            ->field("goods_price,goods_name,goods_num,param,spec_name")
            ->where($where)->select();
        //查询商户名称
        $shopname = db('shop')->where(['id' => $shopid])->field('shopname')->find();
        $goods = $list['order_goods'];

        $orderInfo = '<CB>旺菜通</CB><BR><BR>';
        $orderInfo .= '';
        $orderInfo .= '';
        $orderInfo .= 'ID编号: <CB>' . $list['order_ticket'] . '</CB><BR>';
        $orderInfo .= '';
        $orderInfo .= '商户名: ' . $shopname['shopname'] . '<BR>';
        $orderInfo .= '';
        $orderInfo .= '订单号: ' . $list['order_sn'] . '<BR>';
        $orderInfo .= '';
        if (!empty($list['table_name'])) {
            $orderInfo .= '商家配送线路：' . $list['table_name'] . '<BR>';
            $orderInfo .= '';
        }
        $orderInfo .= '下单时间: ' . date('Y-m-d H:i:s', $list['create_time']) . '<BR>';
        if (!empty($list['delivery_time_start']) && !empty($list['delivery_time_end'])) {
            $orderInfo .= "配送时间: {$list['delivery_time_start']}-{$list['delivery_time_end']}<BR>";
        }
        if ($list['type'] == 1) {
            $orderInfo .= '类型: 预约(' . date('Y-m-d H:i:s', $list['book_time']) . ')<BR>';
        } elseif ($list['type'] == 2) {
            $orderInfo .= '类型: 配送<BR>';
        } elseif ($list['type'] == 3) {
            $orderInfo .= '类型: 扫码点餐<BR>';
        }
        if ($list['pay_type'] == 1) {
            $orderInfo .= '线上支付<BR>';
        } elseif ($list['pay_type'] == 2) {
            $orderInfo .= '线下支付<BR>';
        }
        foreach ($goods as $key => &$value) {
            $value['title'] = $value['goods_name'];
            $value['spec_name'] = $value['spec_name'];
            $value['num'] = $value['goods_num'];
            $value['price'] = $value['goods_price'];
        }
        $orderInfo .= order_print($goods, 14, 6, 3, 6);
        $orderInfo .= '合计：' . $list['total_price'] . '元<BR>';
        $orderInfo .= '联系人：' . $list['realname'] . '<BR>';
        $orderInfo .= '联系电话：' . $list['mobile'] . '<BR>';
        $orderInfo .= '收货地址：' . $shipping_address;
        $shopid = 24; //定死某个商家出订单;
        $type = db('printer')->where(['shop_id' => $shopid,'printer_type' => '1'])->value('type');

        switch ($type) {
            case '1':
                $times = 1;
                break;
            case '2':
                $times = 2;
                break;
        }

        $content = array(
            'user' => USER,
            'stime' => STIME,
            'sig' => SIG,
            'apiname' => 'Open_printMsg',

            'sn' => $printer_sn,
            'content' => $orderInfo,
            'times' => $times//打印次数
        );

        $client = new HttpClient(IP, PORT);

        $message = $this->queryPrinterStatus($printer_sn);

        if (isset($message['message'])) {
            //打印失败
            $update_data['is_print'] = '-1';
            db('order')->where(['id' => $order_id])->update($update_data);
            return 'error';
        } else {
            if (!$client->post(PATH, $content)) {
                //打印失败
                $update_data['is_print'] = '-1';
                db('order')->where(['id' => $order_id])->update($update_data);
                return 'error';
            } else {
                //服务器返回的JSON字符串，建议要当做日志记录起来
                $result = $client->getContent();
                $result = json_decode($result, true);

                $update_data['is_print'] = '1';
                db('order')->where(['id' => $order_id])->update($update_data);
                return $result;
            }
        }
    }

    /**
     * 标签打印
     */
    public function wp_receipt_print($param = '')
    {
        if ($param == '') {

            $shop_id = db('order')->where(['id'=>$this->requestData['order_id']])->value('shop_id');
            $printer = db('printer')->where(['shop_id'=>$shop_id,'printer_type'=>'2'])->find();
            $printer = explode("#", $printer['printer_id']);

            if(empty($printer[0]))return array('message'=>'未绑定打印机');

            //前端调用打印
            $printer_sn = $printer[0];
            $shopid = $this->requestData['shopid'];
            $shipping_address = $this->requestData['shipping_address'];
            $realname = isset($this->requestData['realname']) ? $this->requestData['realname'] : '';
            $mobile = isset($this->requestData['mobile']) ? $this->requestData['mobile'] : '';
            $order_id = $this->requestData['order_id'];

        } else {
            //支付回调直接打印
            $printer_sn = $param['snlist'];
            $shopid = $param['shopid'];
            $shipping_address = $param['shipping_address'];
            $realname = $param['realname'];
            $mobile = $param['mobile'];
            $order_id = $param['order_id'];
        }

        $condition['id'] = $order_id;
        $list = db('order')->where($condition)->find();


        //$orderInfo = "<SIZE>48,58</SIZE>：";

        //标签说明：
        $orderInfo = "<DIRECTION>1</DIRECTION>";//设定打印时出纸和打印字体的方向，n 0 或 1，每次设备重启后都会初始化为 0 值设置，1：正向出纸，0：反向出纸，

        $orderInfo .= "<TEXT x=\"9\" y=\"10\" font=\"11\" w=\"1\" h=\"2\" r=\"0\">             旺菜通      </TEXT>";
        $orderInfo .= "<TEXT x='5' y='80' font='12' w='2' h='2' l='0'> ID编号:{$list['order_ticket']}        </TEXT>";
        if(!empty($list['create_time'])) {
        $orderInfo .= "<TEXT x='5' y='160' font='12' w='1' h='1' r='0' l='0'>下单时间：" . date("Y-m-d H:i:s",$list['create_time']) . "</TEXT>";
        }
        $orderInfo .= "<TEXT x='5' y='220' font='12' w='1' h='1' r='0'>收货人:" . $list['realname'] . "</TEXT>";
        $orderInfo .= "<TEXT x='5' y='280' font='12' w='1' h='1' r='0'>联系电话:" . $list['mobile'] . "</TEXT>";

        $newStr = mb_strlen($list['address'],'UTF-8');

        if($newStr <= 11) {
            $orderInfo .= "<TEXT x='5' y='340' font='12' w='1' h='1' r='0'>收货地址:" . $list['address'] . "</TEXT>";
        }else{
            $address = $list['address'];

            $address_one = mb_substr($address, 0, 11);
            $address_two = mb_substr($address, 11);

            $orderInfo .= "<TEXT x='5' y='340' font='12' w='1' h='1' r='0'>收货地址:" . $address_one . "</TEXT>";
            $orderInfo .= "<TEXT x='5' y='400' font='12' w='1' h='1' r='0'>".$address_two ."</TEXT>";
        }

        $content = array(
            'user' => USER,
            'stime' => STIME,
            'sig' => SIG,
            'apiname' => 'Open_printLabelMsg',
            'sn' => $printer_sn,
            'content' => $orderInfo,
            'times' => 0//打印次数
        );

        $client = new HttpClient(IP, PORT);

        $message = $this->queryPrinterStatus($printer_sn);

        if (!isset($message['message'])) {
            if (!$client->post(PATH, $content)) {
                //服务器返回的JSON字符串，建议要当做日志记录起来
                $result = $client->getContent();
                $result = json_decode($result, true);
                return $result;
            }
        }
    }

    //配送地址列表
    public function address_list()
    {
        $shop_id = $this->user['shopid'];
        $sel = db('give_address')->where(["shop_id" => $shop_id])->select();
        return $sel;
    }

    //添加配送地址(修改配送地址)
    public function address_edit()
    {
        $shop_id = $this->user['shopid'];
        $res = $this->checkData(
            ["province", "city", "county", "street"],
            ["省份不能为空", "城市不能为空", "区域不能为空", "街道不能为空"]
        );
        if (array_key_exists('message', $res)) return $res;

        $province = $this->requestData["province"];
        $city = $this->requestData["city"];
        $area = $this->requestData["county"];
        $street = $this->requestData["street"];

        $data = array(

            'province' => $province,
            'city' => $city,
            'country' => $area,
            'street' => $street,
            'shop_id' => $shop_id,
        );
        if (!array_key_exists('id', $this->requestData)) {
            if (!db('give_address')->insert($data)) return array('message' => '添加失败');
        } else {
            if (db('give_address')->where(['id' => intval($this->requestData['id'])])->update($data) === false) return array('message' => '更新失败');
        }
        return array();
    }

    //删除配送地址
    public function address_del()
    {
        $shop_id = $this->user['shopid'];
        $res = $this->checkData(
            ["id"],
            ["配送地址ID不能为空"]
        );
        if (array_key_exists('message', $res)) return $res;
        $addressid = intval($this->requestData["id"]);
        $sel = db('give_address')->where(["id" => $addressid, "shop_id" => $shop_id])->find();
        if (!$sel) {
            return array('message' => "收货地址不存在");
        }
        if (!db('give_address')->where(["shop_id" => $shop_id, "id" => $addressid])->delete()) return array('message' => "删除失败");
        return array();
    }

    //分佣明细
    public function commission_detail()
    {
        $shop_id = $this->user['shopid'];
        $page = isset($this->requestData["page"]) ? $this->requestData["page"] : '1';
        $member_balance = db('member_balance')->alias('mb')->join('order o', 'o.id=mb.order_id')->where(['mb.shop_id' => $shop_id])->page("{$page},10")->field("mb.*,o.total_price")->select();

        foreach ($member_balance as $key => $value) {
            $member = db('member')->where(['id' => $value['uid']])->field('headimage,nickname')->find();
            $member_balance[$key]['headimage'] = $member['headimage'];
            $member_balance[$key]['nickname'] = $member['nickname'];
        }

        return $member_balance;
    }

    //自提返利
    public function mention_commission_detail()
    {
        $shop_id = $this->user['shopid'];
        $page = isset($this->requestData["page"]) ? $this->requestData["page"] : '1';
        $member_balance = db('mention_balance')->alias('mb')->join('order o', 'o.id=mb.order_id')->where(['mb.shop_id' => $shop_id])->page("{$page},10")->field("mb.money,mb.uid,mb.money,mb.status,o.order_sn")->select();

        foreach ($member_balance as $key => $value) {
            $member = db('member')->where(['id' => $value['uid']])->field('headimage,nickname')->find();
            $member_balance[$key]['headimage'] = $member['headimage'];
            $member_balance[$key]['nickname'] = $member['nickname'];
        }

        return $member_balance;
    }
}